<template>
  <el-dialog
    :visible="visible"
    :center="true"
    :modal="modal"
    :modal-append-to-body="false"
    title="编辑资料"
    width="400px"
    class="edit-form"
    @close="visible = false"
  >
    <div class="edit-form-item edit-avatar-dialog">
      <div class="edit-avatar">
        <el-upload
          class="avatar-uploader"
          :action="editForm.avatar || ''"
          :http-request="uploadAvatar"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <el-avatar :src="editForm.avatar" :size="80"> </el-avatar>
        </el-upload>
      </div>

      <div class="edit-name-wrap">
        <div class="edit-nickname" :style="{ width: `${inputWidth}px` }">
          <el-input
            v-model="editForm.nickname"
            :placeholder="nicknamePlaceholder"
            :maxlength="16"
            :style="{ 'font-size': `${nicknameFontsize}px` }"
          ></el-input>

          <div
            class="edit-gender inline-flex"
            :style="{ left: `${genderOffset}px` }"
          >
            <span
              v-for="item in genderList"
              :key="item.index"
              class="gender-choice"
              @click="handleClickGender(item)"
            >
              <i
                v-show="selectGenderMode || editForm.gender === item.index"
                :class="item.iconClass"
                :style="{
                  color: editForm.gender === item.index ? item.color : '#ccc',
                  'font-weight': 500,
                }"
              ></i>
            </span>
          </div>
        </div>
      </div>

      <div class="edit-desc">
        <el-input
          v-model="editForm.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 10 }"
        >
        </el-input>
      </div>

      <div class="edit-submit-btns">
        <el-button type="primary" @click="submitEdit">提交修改</el-button>
        <el-button type="danger" @click="submitLogout">退出登录</el-button>
      </div>
    </div>

    <template v-slot:footer>
      <div style="color: #cccccc; font-size: 14px;">
        <div>
          本站采用企业级OAuth2认证系统
        </div>
        <div>
          请放心注册与登录~
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import deepCopy from 'deepcopy'
import deepEqual from 'deep-equal'

export default {
  name: 'NcEditDialog',
  props: {
    modal: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      visible: false,
      editForm: {
        avatar: '',
        nickname: '',
        gender: 0,
        description: '这是一位狼人……',
      },
      editFormBackup: {},
      submitInterval: 10000, // 毫秒,
      selectGenderMode: false,
      genderList: [
        {
          index: 0,
          iconClass: 'el-icon-key',
          color: 'gold',
        },
        {
          index: 1,
          iconClass: 'el-icon-male',
          color: 'blue',
        },
        {
          index: 2,
          iconClass: 'el-icon-female',
          color: 'pink',
        },
      ],
      nicknameFontsize: 24,
      nicknamePlaceholder: '还记得你的名字吗~',
      genderOffsetMax: 300,
    }
  },
  computed: {
    inputWidth() {
      return (
        this.nicknameFontsize *
        ((this.editForm.nickname || this.nicknamePlaceholder).length + 1)
      )
    },
    genderOffset() {
      return this.inputWidth < this.genderOffsetMax
        ? this.inputWidth
        : this.genderOffsetMax
    },
  },
  methods: {
    handleOpen() {
      this.visible = true
      console.log('opened dialog')
      // 一一赋值（由于与数据库结构不匹配）
      Object.assign(this.editForm, this.$store.state.user)
      this.editFormBackup = deepCopy(this.editForm)
    },
    handleClose() {
      this.visible = false
      console.log('closed edit dialog')
    },

    beforeAvatarUpload(file) {
      const imgTypeMeet = ['image/jpeg', 'image/png'].includes(file.type)
      const imgSizeMeet = file.size < 2 * 1024 * 1024

      if (!imgTypeMeet) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!imgSizeMeet) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return imgTypeMeet && imgSizeMeet
    },
    uploadAvatar({ file }) {
      const _this = this
      this.$putImg(file.uid, file)
        .then((imgUrl) => {
          console.log({ imgUrl })
          _this.editForm.avatar = imgUrl
        })
        .catch((err) => {
          console.log('err', err)
        })
    },
    checkSubmitInterval(timeInterval) {
      const lastTime = this.$store.state.user.updateTime
      return !(lastTime && lastTime + timeInterval > new Date().getTime())
    },

    submitEdit() {
      console.log('try to update user data')
      if (!this.checkSubmitInterval(this.submitInterval)) {
        return this.$message.error('您变脸太快啦，要不慢一点吧~')
      }
      if (deepEqual(this.editForm, this.editFormBackup)) {
        return this.$message.error('不要逗我啦，您好像什么都没有做呢~')
      }
      if (!this.editForm.nickname) {
        return this.$message.error('可以用你的名字呼唤我吗~')
      }

      this.$http
        .put(this.$api.apps.user.update.path, this.editForm)
        .then((res) => {
          console.log('res', res)
          this.$store.commit('SET_USER', {
            ...this.editForm,
            updateTime: new Date().getTime(),
          })
          this.handleClose()
          this.$message.success('修改成功~')
        })
        .catch((err) => {
          console.log('err', err)
          this.$message.error(err.response.data.detail)
        })
    },

    async submitLogout() {
      console.log('try to log out')
      this.$store.commit('RESET_USER')
      await this.$http.get(this.$api.apps.user.logout.path)
      this.handleClose()
      this.$message.success('退出成功！')
    },

    handleClickGender(item) {
      this.selectGenderMode = !this.selectGenderMode
      if (!this.selectGenderMode) {
        this.editForm.gender = item.index
      }
    },
  },
}
</script>

<style lang="less" scoped>
.edit-avatar-dialog {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .edit-avatar {
  }

  .edit-name-wrap {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;
    max-width: 80%;

    .edit-nickname {
      position: relative;

      /deep/ .el-input {
        font-weight: 400;

        .el-input__inner {
          border: none;
          text-align: center;
          padding: 0;
        }
      }

      .edit-gender {
        position: absolute;
        left: -24px;
        top: 2px;
        font-size: 24px;
      }
    }
  }

  .edit-desc {
    font-size: 20px;
    margin-bottom: 20px;

    .el-textarea__inner {
      text-align: center !important;
    }
  }

  .edit-submit-btns {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
